package com.sunfeng.n5;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 同步模式之Balking模式
 *
 * @author sunfeng
 * @date 2021/04/13 16:27
 **/
@Slf4j(topic = "c.MonitorService")
public class MonitorService {

    /**
     * 用来表示是否已经有线程已经在执行启动了
     */
    private volatile boolean starting;

    private volatile boolean stop;

    private  Thread monitorThread;

    public static void main(String[] args) throws InterruptedException {
        MonitorService monitorService = new MonitorService();

        Thread t1 = new Thread(() -> {
            monitorService.start();
        }, "t1");
        t1.start();
        Thread t2 = new Thread(() -> {
            monitorService.start();
        }, "t2");
        t2.start();
        Thread t3 = new Thread(() -> {
            monitorService.start();
        }, "t3");
        t3.start();


        TimeUnit.SECONDS.sleep(5);
        monitorService.stop();
    }

    public void start() {
        log.info("尝试启动监控线程...");
        synchronized (this) {
            log.debug("线程是否已经启动？：{}", starting);
            if (starting) {
                return;
            }
            starting = true;
        }
        // 真正启动监控线程...
        monitorThread = new Thread(() -> {
            while (!stop) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    log.debug("执行监控操作");
                } catch (InterruptedException e) {
                   log.debug("监控线程开始停止");
                }
            }
            log.debug("监控线程已经停止");
            stop = false;
        }, "监控线程");

        stop = false;

        log.debug("监控线程已经启动");

        monitorThread.start();

    }

    public void stop() {
        stop = true;
        monitorThread.interrupt();
    }
}
